'use client';

import { useToast } from '@/hooks/use-toast';
import { genShopImageKey } from '@/lib/cos';
import { result } from '@/lib/utils';
import { useCosClient } from '@/providers/cos-provider';
import { updateShopImageKeys } from '@/service/actions/shop';
import ImageUploader from '../common/image-uploader';
import QueryImage from '../common/query-image';
import { Button } from '../ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../ui/dialog';
import ImagePopover from './image-popover';

export default function ShopImageUpload({
  userId,
  imageKeys,
}: { userId: string; imageKeys: string[] }) {
  const { toast } = useToast();
  const cosClient = useCosClient();

  const onUpdate = async (keys: string[], type: 'add' | 'delete') => {
    if (type === 'add') {
      const { error } = await updateShopImageKeys([...imageKeys, ...keys]);
      error
        ? toast({ title: error.message, variant: 'destructive' })
        : toast({ title: '上传成功' });
      return error ? result(error, error.message) : result();
    }
    const { error } = await updateShopImageKeys(
      imageKeys.filter((k) => !keys.includes(k)),
    );
    error
      ? toast({ title: error.message, variant: 'destructive' })
      : toast({ title: '删除成功' });
    !error && cosClient?.delete(keys);
    return error ? result(error, error.message) : result();
  };

  return (
    <Dialog>
      <DialogTrigger asChild>
        <Button>上传图片</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader className="space-y-4">
          <DialogTitle>上传图片</DialogTitle>
          <DialogDescription>为商铺上传图片</DialogDescription>
        </DialogHeader>
        <div className="flex flex-wrap gap-3 items-center">
          {imageKeys.length ? (
            imageKeys.map((imageKey) => (
              <ImagePopover
                key={imageKey}
                imageKey={imageKey}
                onDelete={() => onUpdate([imageKey], 'delete')}
              >
                <QueryImage
                  key={imageKey}
                  imageKey={imageKey}
                  wrapperClassName="w-36 h-32"
                  imgClassName="w-full h-full object-cover"
                />
              </ImagePopover>
            ))
          ) : (
            <div className="col-span-4 text-center py-5">暂无图片</div>
          )}
        </div>
        <ImageUploader
          button={<Button>上传图片</Button>}
          onUploaded={(keys) => onUpdate(keys, 'add')}
          genImageKey={() => genShopImageKey(userId)}
        />
      </DialogContent>
    </Dialog>
  );
}
